/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.istia.gesstages.actions;

import com.opensymphony.xwork2.ActionSupport;
import fr.istia.gesstages.dao.IDaoUser;
import fr.istia.gesstages.exception.PortailException;
import fr.istia.gesstages.jpa.User;
import fr.istia.gesstages.util.Access;
import fr.istia.gesstages.util.Encryption;
import java.util.Map;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

/**
 *
 * @author Gaëtan
 */
@SuppressWarnings("serial")
public class LoginAction extends ActionSupport implements SessionAware {

    private IDaoUser beanDaoUser;
    private Access beanAccess;
    private Map<String, Object> session;
    private String user;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    @Override
    public String execute() {
        return "success";
    }

    public String validateLogin() {
        try {
            if (beanAccess.login(this.user, Encryption.md5(this.password))) {
                User user = beanDaoUser.find(this.user);
                if (user.getType().getLibelle().equals("Administrateur")) {
                    return "admin";
                } else {
                    return "user";
                }
            } else {
                addFieldError("login.password", getText("login.error.password"));
                return "input";
            }
        } catch (PortailException e) {
            addFieldError("login.user", getText("login.error.user"));
            return "input";
        }
    }

    public void setSession(Map<String, Object> map) {
        this.session = map;
    }

    public String disconnect() {
        if (session instanceof SessionMap) {
            try {
                ((SessionMap<String, Object>) session).invalidate();
                return "success";
            } catch (IllegalStateException e) {
                addFieldError("login.error.disconnect", getText("login.error.disconnect"));
                return "input";
            }
        } else {
            addFieldError("login.error.disconnect.nosession", getText("login.error.disconnect.nosession"));
            return "input";
        }
    }

    public Access getBeanAccess() {
        return beanAccess;
    }

    public void setBeanAccess(Access beanAccess) {
        this.beanAccess = beanAccess;
    }


    public IDaoUser getBeanDaoUser() {
        return beanDaoUser;
    }

    public void setBeanDaoUser(IDaoUser beanDaoUser) {
        this.beanDaoUser = beanDaoUser;
    }

}
